package search

import (
	"errors"
	"fmt"
	"reflect"
)

//二分查找,要查找的字段值只能是int类型,datas需按colname升序
func Search(datas interface{}, colname string, id int64) (t interface{}, err error) {
	rvf := reflect.ValueOf(datas)
	if rvf.Kind() != reflect.Slice {
		return nil, errors.New("datas必需是切片")
	}

	left := 0
	right := rvf.Len() - 1
	for right > 0 && left < rvf.Len() {
		mid := (right + left) / 2
		rowData := rvf.Index(mid)
		colval := rowData.FieldByName(colname)
		if !colval.IsValid() {
			return nil, errors.New(fmt.Sprintf("第%d行没有要查找的字段", mid))
		}
		intval := colval.Int()
		if intval == id {
			return rowData, nil
		}
		if intval > id {
			right = mid - 1
			continue
		}
		if intval < id {
			left = mid + 1
			continue
		}

	}
	return nil, nil
}

//二分查找,要查找的字段值只能是int类型,datas需按colname升序
func SearchString(datas interface{}, colname string, str string) (t interface{}, err error) {
	rvf := reflect.ValueOf(datas)
	if rvf.Kind() != reflect.Slice {
		return nil, errors.New("datas必需是切片")
	}


	for i := 0; i < rvf.Len(); i++ {
		rowData := rvf.Index(i)
		colval := rowData.FieldByName(colname)
		if !colval.IsValid() {
			return nil, errors.New(fmt.Sprintf("第%d行没有要查找的字段", i))
		}
		if colval.Kind() != reflect.String {
			return nil, errors.New(fmt.Sprintf("第%d行的字段值不是String", i))
		}
		intval := colval.String()
		if intval == str {
			return rowData, nil
		}

	}
	return nil, errors.New("未找到")
}
